<?php
declare (strict_types=1);

namespace app\admin\model\wechat;

use app\admin\model\BaseModel;

class Auth extends BaseModel
{
    //当前模型对应的数据表名称
    protected $name = 'wechat_auth';

    public function getList($filter = []): array
    {
        $where = function ($query) use ($filter) {
            if (isset($filter['account'])) {
                $query->where('account', 'like', '%' . $filter['account'] . '%');
            }
            if (isset($filter['status'])) {
                $query->where('status', '=', $filter['status']);
            }
        };
        $order = ['id' => 'desc'];
        return self::getPageList($where, $order);
    }

    /**
     * 获取采集所需的token和cookie
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAuthInfo(): array
    {
        $ids = self::where('status', '=', 1)->column('id');
        if ($ids) {
            shuffle($ids);
            $auth = self::where('id', '=', $ids[0])->find();
            $token = $auth['token'];
            $cookie = $auth['cookie'];
        } else {
            $token = '';
            $cookie = '';
        }

        return [$token, $cookie];
    }

    /*
     * 更新token的状态-失效
     */
    public static function updateAuth($token)
    {
        $arrData = [
            'status' => 0,
            'updatetime' => time(),
        ];
        return self::where('token', '=', $token)->save($arrData);
    }

}